#include "inputs/command.h"

namespace dw {
	namespace inputs {

InputCommand::InputCommand()
:	m_isActive(false)
{
}

InputCommand::~InputCommand()
{
	for (SamplersCollection::iterator samplerIt = m_samplers.begin(); samplerIt != m_samplers.end(); ++samplerIt)
	{
		delete *samplerIt;
	}

	m_samplers.clear();

	for (ConditionsCollection::iterator conditionIt = m_conditions.begin(); conditionIt != m_conditions.end(); ++conditionIt)
	{
		delete *conditionIt;
	}

	m_conditions.clear();
}

void InputCommand::addCondition(const InputCondition& condition)
{
	m_conditions.push_back(condition.clone());
}

void InputCommand::addSampler(const InputSampler& sampler)
{
	m_samplers.push_back(sampler.clone());
}

bool InputCommand::isActive() const
{
	return m_isActive;
}

dw::float32 InputCommand::getValue(const dw::uint32 samplerId) const
{
	dwAssert(samplerId < m_samplers.size(), "Invalid parameter: samplerId is out of range");

	return m_isActive ?
		m_samplers[samplerId] != NULL ? m_samplers[samplerId]->getValue() : 1.0f :
		0.0f;
}

void InputCommand::update(const OIS::Keyboard* keyboard, const OIS::Mouse* mouse)
{
	dwAssert(keyboard != NULL, "Invalid keyboard");
	dwAssert(mouse != NULL, "Invalid mouse");

	m_isActive = true;

	for (ConditionsCollection::iterator conditionIt = m_conditions.begin(); conditionIt != m_conditions.end(); ++conditionIt)
	{
		InputCondition* condition = *conditionIt;

		dwAssert(condition != NULL, "Invalid condition");

		if (condition->getDeviceType() == keyboard->type())
		{
			condition->update(keyboard);
		}
		else if (condition->getDeviceType() == mouse->type())
		{
			condition->update(mouse);
		}

		m_isActive = m_isActive && condition->isActive();
	}

	if (m_isActive && m_samplers.size() > 0)
	{
		for (SamplersCollection::iterator samplerIt = m_samplers.begin(); samplerIt != m_samplers.end(); ++samplerIt)
		{
			if ((*samplerIt)->getDeviceType() == keyboard->type())
			{
				(*samplerIt)->update(keyboard);
			}
			else if ((*samplerIt)->getDeviceType() == mouse->type())
			{
				(*samplerIt)->update(mouse);
			}
		}
	}
}

	} // namespace inputs
} // namespace dw
